package com.yy.micro.magic.type;

import com.fasterxml.jackson.annotation.JsonValue;

import java.io.Serializable;

public interface PersistableEnum<V> extends Serializable {

    static <T extends PersistableEnum, V> T valueOf(V value, Class<T> clazz) {
        T constant = resolve(value, clazz);
        if (constant == null) {
            throw new IllegalArgumentException("No matching constant for " + clazz.getCanonicalName() + ".[" + value + "]");
        }
        return constant;

    }

    static <T extends PersistableEnum, V> T resolve(V value, Class<T> clazz) {
        T[] values = clazz.getEnumConstants();
        for (T e : values) {
            if (e.value().equals(value)) {
                return e;
            }
        }

        return null;
    }

    @JsonValue
    V value();
}
